home *** CD-ROM | disk | FTP | other *** search
/ C & C++ Multimedia Cyber Classroom / C and C++ Multimedia Cyber Classroom (Prentice Hall) (1998).iso / src / fig07_09.jar / Ch07 / Fig07_09 / Employ1.cpp next >
C/C++ Source or Header  |  1997-10-20  |  2KB  |  61 lines

  1. // Fig. 7.9: employ1.cpp
  2. // Member function definitions for class Employee
  3. #include <iostream.h>
  4. #include <string.h>
  5. #include <assert.h>
  6. #include "employ1.h"
  7.  
  8. // Initialize the static data member
  9. int Employee::count = 0;
  10.  
  11. // Define the static member function that
  12. // returns the number of employee objects instantiated.
  13. int Employee::getCount() { return count; }
  14.  
  15. // Constructor dynamically allocates space for the
  16. // first and last name and uses strcpy to copy
  17. // the first and last names into the object
  18. Employee::Employee( const char *first, const char *last )
  19. {
  20.    firstName = new char[ strlen( first ) + 1 ];
  21.    assert( firstName != 0 );   // ensure memory allocated
  22.    strcpy( firstName, first );
  23.  
  24.    lastName = new char[ strlen( last ) + 1 ];
  25.    assert( lastName != 0 );    // ensure memory allocated
  26.    strcpy( lastName, last );
  27.  
  28.    ++count;  // increment static count of employees
  29.    cout << "Employee constructor for " << firstName
  30.         << ' ' << lastName << " called." << endl;
  31. }
  32.  
  33. // Destructor deallocates dynamically allocated memory
  34. Employee::~Employee()
  35. {
  36.    cout << "~Employee() called for " << firstName
  37.         << ' ' << lastName << endl;
  38.    delete firstName;  // recapture memory
  39.    delete lastName;   // recapture memory
  40.    --count;  // decrement static count of employees
  41. }
  42.  
  43. // Return first name of employee
  44. const char *Employee::getFirstName() const
  45. {
  46.    // Const before return type prevents client modifying
  47.    // private data. Client should copy returned string before
  48.    // destructor deletes storage to prevent undefined pointer.
  49.    return firstName;
  50. }
  51.  
  52. // Return last name of employee
  53. const char *Employee::getLastName() const
  54. {
  55.    // Const before return type prevents client modifying
  56.    // private data. Client should copy returned string before
  57.    // destructor deletes storage to prevent undefined pointer.
  58.    return lastName;
  59. }
  60.  
  61.